package com.example.fq.s3;

import android.util.Log;
import android.widget.Toast;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

/**
 * Created by fq on 15-5-10.
 */
public class HttpUtil {
    private static final int RESPONSE = 0;

    public static void sendHttpRequest(final String query, final HttpCallbackListener listener) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                String address = null;
                try {
                    address = "http://sou.api.autohome.com.cn/v2/global/search" +
                            "?Sort=" +
                            "&Author=0" +
                            "&q=" + URLEncoder.encode(query, "UTF-8") +
                            "&s=1" +
                            "&_appid=sou" +
                            "&HL=36%2C82_1_title%2Ccontent_em%2Cem" +
                            "&offset=0" +
                            "&type=0" +
                            "&Class=" +
                            "&size=10";
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                try {

                    URL url = new URL(address);
                    Log.d("msg6", address);
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    connection.setDoInput(true);
                    connection.setDoOutput(true);

                    InputStream in = connection.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }


                    if (listener != null) {
                        listener.onFinish(response.toString());
                    }
                } catch (Exception e) {
                    if (listener != null) {
                        listener.onError(e);
                    }
                }
            }
        }).start();
    }

}
